package ar.com.ford.it.fullEconomics.view.action;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.LinkedList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.FullEconomicsPrs;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.CommodityFacade;
import ar.com.ford.it.fullEconomics.facade.CostStructureFacade;
import ar.com.ford.it.fullEconomics.facade.FullEconomicsFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesc02Coststvers;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesc03Subcoststr;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesf01Fulleconom;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr01Request;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr02Requestitm;
import ar.com.ford.it.fullEconomics.struct.FullEconomicsExcercisesStruct;
import ar.com.ford.it.fullEconomics.struct.OptionCombo;
import ar.com.ford.it.fullEconomics.util.XlsPrinter;
import ar.com.ford.it.fullEconomics.view.form.FullEconomicsExcercisesForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

public class FullEconomicsExcercisesAction extends AbstractBaseAction {

    /**
     * 
     * @return Coleccion de posibles estados de Cost Structure
     */
    private Collection getComboStatus(HttpServletRequest request) {
        LinkedList<OptionCombo> list = new LinkedList<OptionCombo>();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        list.add(new OptionCombo("Draft", resources.getMessage("label.draft")));
        list.add(new OptionCombo("Proposed", resources
                .getMessage("label.proposed")));
        list.add(new OptionCombo("Approved", resources
                .getMessage("label.approved")));

        return list;
    }

    /**
     * 
     * @param request
     * @return
     */
    private Collection<OptionCombo> getComboSupplierClasses(
                                                            HttpServletRequest request) {
        LinkedList<OptionCombo> list = new LinkedList<OptionCombo>();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        list.add(new OptionCombo("F", resources.getMessage("label.ford")));
        list.add(new OptionCombo("C", resources.getMessage("label.custom")));

        return list;
    }

    /**
     * 
     * @param request
     * @return
     */
    private Collection<OptionCombo> getComboPartClasses(
                                                        HttpServletRequest request) {
        LinkedList<OptionCombo> list = new LinkedList<OptionCombo>();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        list.add(new OptionCombo("F", resources.getMessage("label.ford")));
        list.add(new OptionCombo("C", resources.getMessage("label.custom")));

        return list;
    }

    /**
     * 
     * @param request
     * @return
     */
    private Collection<OptionCombo> getComboDateTypes(HttpServletRequest request) {
        LinkedList<OptionCombo> list = new LinkedList<OptionCombo>();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        list.add(new OptionCombo("Creation", resources
                .getMessage("user.label.creation")));
        list.add(new OptionCombo("Proposal", resources
                .getMessage("user.label.proposal")));
        list.add(new OptionCombo("Approval", resources
                .getMessage("user.label.approval")));
        list.add(new OptionCombo("EffDateIn", resources
                .getMessage("label.effDateIn")));

        return list;
    }

    /**
     * 
     * @param request
     * @return
     */
    private Collection<OptionCombo> getComboUserActionTypes(
                                                            HttpServletRequest request) {
        LinkedList<OptionCombo> list = new LinkedList<OptionCombo>();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        list.add(new OptionCombo("Creation", resources
                .getMessage("user.label.creation")));
        list.add(new OptionCombo("Proposal", resources
                .getMessage("user.label.proposal")));
        list.add(new OptionCombo("Approval", resources
                .getMessage("user.label.approval")));

        return list;
    }

    /**
     * Inicializa la pagina de Full Economics Excersices
     */
    public ActionForward initPage(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {
        FullEconomicsExcercisesForm form = (FullEconomicsExcercisesForm) actionForm;
        CommodityFacade commodityFacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();

        try {
            form.resetForm();
            request.getSession().setAttribute("statusCol",
                    this.getComboStatus(request));
            request.getSession().setAttribute("supplierTypeCol",
                    this.getComboSupplierClasses(request));
            request.getSession().setAttribute("partClassesCol",
                    this.getComboPartClasses(request));
            request.getSession().setAttribute(
                    "commoditiesCol",
                    commodityFacade.findCommodities("", "", user
                            .getTeesg01Plant()));
            request.getSession().setAttribute("userActionsTypesCol",
                    this.getComboUserActionTypes(request));
            request.getSession().setAttribute("dateTypesCol",
                    this.getComboDateTypes(request));
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * Genera la busqueda de los full Economics que cumplan con los parametros
     * seleccionados
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward findFullEconomicsExcercises(
                                                     FordActionMapping mapping,
                                                     ActionForm actionForm,
                                                     HttpServletRequest request,
                                                     HttpServletResponse response,
                                                     WebSession webSession,
                                                     ActionMessages msgs,
                                                     ActionMessages warns,
                                                     ActionMessages errorMsgs) {

        FullEconomicsExcercisesForm form = (FullEconomicsExcercisesForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();

        FullEconomicsFacade facade = (FullEconomicsFacade) FacadeProvider
                .getFacade(request, FullEconomicsFacade.class);

        FullEconomicsExcercisesStruct parameters = form.getFindParameters(user);

        try {
            form.setFullEconomics(facade.getFullEconomicsCol(parameters));
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * Redirecciona a la pagina de full economics, con el full economic
     * seleccionado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward viewFullEconomicsExcercises(
                                                     FordActionMapping mapping,
                                                     ActionForm actionForm,
                                                     HttpServletRequest request,
                                                     HttpServletResponse response,
                                                     WebSession webSession,
                                                     ActionMessages msgs,
                                                     ActionMessages warns,
                                                     ActionMessages errorMsgs) {

        FullEconomicsExcercisesForm form = (FullEconomicsExcercisesForm) actionForm;

        request.setAttribute("fullEconomicSelected", form
                .getTeesf01FulleconomSelected());

        return mapping.findForward("success");
    }

    /**
     * Redirecciona a la pagina de request con el proveedor del full economic
     * seleccionado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward viewFullEconomicsExcercisesRequest(
                                                            FordActionMapping mapping,
                                                            ActionForm actionForm,
                                                            HttpServletRequest request,
                                                            HttpServletResponse response,
                                                            WebSession webSession,
                                                            ActionMessages msgs,
                                                            ActionMessages warns,
                                                            ActionMessages errorMsgs) {

        FullEconomicsExcercisesForm form = (FullEconomicsExcercisesForm) actionForm;

        request.setAttribute("requestSelected", form
                .getTeesf01FulleconomSelected().getTeesr02Requestitm()
                .getTeesr01Request());

        return mapping.findForward("success");
    }

    /**
     * Elimina un Full Economic
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward deleteFullEconomicsExcercises(
                                                       FordActionMapping mapping,
                                                       ActionForm actionForm,
                                                       HttpServletRequest request,
                                                       HttpServletResponse response,
                                                       WebSession webSession,
                                                       ActionMessages msgs,
                                                       ActionMessages warns,
                                                       ActionMessages errorMsgs) {

        FullEconomicsExcercisesForm form = (FullEconomicsExcercisesForm) actionForm;

        FullEconomicsFacade facade = (FullEconomicsFacade) FacadeProvider
                .getFacade(request, FullEconomicsFacade.class);

        try {
            facade.deleteFullEconomics(form.getTeesf01FulleconomSelected());
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * Propone un Full Economic
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward proposeFullEconomicsExcercises(
                                                        FordActionMapping mapping,
                                                        ActionForm actionForm,
                                                        HttpServletRequest request,
                                                        HttpServletResponse response,
                                                        WebSession webSession,
                                                        ActionMessages msgs,
                                                        ActionMessages warns,
                                                        ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        FullEconomicsExcercisesForm form = (FullEconomicsExcercisesForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();

        FullEconomicsFacade facade = (FullEconomicsFacade) FacadeProvider
                .getFacade(request, FullEconomicsFacade.class);
        CostStructureFacade cstFacade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);

        try {
            Teesc02Coststvers costStrVers = form.getTeesf01FulleconomSelected()
                    .getTeesc02Coststvers();
            boolean allOk = true;
            if (costStrVers.getEesc02CststvProposalUserC() == null) {
                Teesc03Subcoststr incompSubCostStr = cstFacade
                        .getIncompleteSubCostStr(form
                                .getTeesf01FulleconomSelected()
                                .getTeesc02Coststvers().getTeesc03Subcoststr());
                if (incompSubCostStr != null) {
                    am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "fullEconomics.error.incompleteCostStructure",
                            incompSubCostStr.getEesc03SubcstNameN()));
                    saveErrors(request, am);
                    allOk = false;
                } else {
                    am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "fullEconomics.warning.proposeCostStr", costStrVers
                                    .getTeesc01Coststruct()
                                    .getEesc01CststrNumberK().toString()
                                    + "."
                                    + costStrVers
                                            .getEesc02CststvVersionNumberK()
                                            .toString()));
                    saveMessages(request, am);
                }
            }
            if (allOk) {

                facade.proposeFullEconomics(
                        form.getTeesf01FulleconomSelected(), user);
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * Aprueba un Full Economic
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward approveFullEconomicsExcercises(
                                                        FordActionMapping mapping,
                                                        ActionForm actionForm,
                                                        HttpServletRequest request,
                                                        HttpServletResponse response,
                                                        WebSession webSession,
                                                        ActionMessages msgs,
                                                        ActionMessages warns,
                                                        ActionMessages errorMsgs) {

        FullEconomicsExcercisesForm form = (FullEconomicsExcercisesForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();

        FullEconomicsFacade facade = (FullEconomicsFacade) FacadeProvider
                .getFacade(request, FullEconomicsFacade.class);

        try {
            Teesf01Fulleconom teesf01Fulleconom = form
                    .getTeesf01FulleconomSelected();

            facade.approveFullEconomics(teesf01Fulleconom, user);
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            if (e.getArgument() != null)
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                        .getMessageResource(), e.getArgument()));
            else
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                        .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * Aprueba un Full Economic
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward fullEconomicSetRequest(FordActionMapping mapping,
                                                ActionForm actionForm,
                                                HttpServletRequest request,
                                                HttpServletResponse response,
                                                WebSession webSession,
                                                ActionMessages msgs,
                                                ActionMessages warns,
                                                ActionMessages errorMsgs) {

        FullEconomicsExcercisesForm form = (FullEconomicsExcercisesForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();

        FullEconomicsFacade facade = (FullEconomicsFacade) FacadeProvider
                .getFacade(request, FullEconomicsFacade.class);
        Integer fulleCode = new Integer(request.getParameter("fulleCode"));
        Integer requestCode = new Integer(request.getParameter("requestCode"));
        Integer itemCode = new Integer(request.getParameter("itemCode"));
        Teesr01Request teesr01Request = new Teesr01Request();
        teesr01Request.setEesr01PlantCodeC(user.getTeesg01Plant());
        teesr01Request.setEesr01RequestNumberK(requestCode);
        Teesr02Requestitm requestItem = new Teesr02Requestitm();
        requestItem.setEesr02PlantCodeC(user.getTeesg01Plant());
        requestItem.setEesr02ReqitmNumberK(itemCode);
        requestItem.setTeesr01Request(teesr01Request);

        try {
            Teesf01Fulleconom teesf01Fulleconom = new Teesf01Fulleconom();
            teesf01Fulleconom.setEesf01PlantCodeC(user.getTeesg01Plant());
            teesf01Fulleconom.setEesf01FulleNumberK(fulleCode);

            facade.setRequestItem(teesf01Fulleconom, requestItem);
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            if (e.getArgument() != null)
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                        .getMessageResource(), e.getArgument()));
            else
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                        .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * Rechaza un Full Economic
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward rejectFullEconomicsExcercises(
                                                       FordActionMapping mapping,
                                                       ActionForm actionForm,
                                                       HttpServletRequest request,
                                                       HttpServletResponse response,
                                                       WebSession webSession,
                                                       ActionMessages msgs,
                                                       ActionMessages warns,
                                                       ActionMessages errorMsgs) {

        FullEconomicsExcercisesForm form = (FullEconomicsExcercisesForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();

        FullEconomicsFacade facade = (FullEconomicsFacade) FacadeProvider
                .getFacade(request, FullEconomicsFacade.class);

        try {
            Teesf01Fulleconom teesf01Fulleconom = form
                    .getTeesf01FulleconomSelected();
            if (teesf01Fulleconom.getEesf01FulleProposalUserC().equals(
                    user.getId())) {
                ActionMessages am = new ActionMessages();
                am
                        .add(
                                ActionMessages.GLOBAL_MESSAGE,
                                new ActionMessage(
                                        FullEconomicsPrs.MessageErrors.FullEconomics.REJECT_USER));
                saveErrors(request, am);
            } else {
                if (teesf01Fulleconom.getEesf01FulleRejectUserC() != null) {
                    ActionMessages am = new ActionMessages();
                    am
                            .add(
                                    ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage(
                                            FullEconomicsPrs.MessageErrors.FullEconomics.REJECT_ALREADY));
                    saveErrors(request, am);
                } else {
                    facade.rejectFullEconomics(teesf01Fulleconom, user);
                }
            }
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * Genera un reporte en excel de los agreements seleccionados en el filtro
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward reportFullEconomic(FordActionMapping mapping,
                                            ActionForm actionForm,
                                            HttpServletRequest request,
                                            HttpServletResponse response,
                                            WebSession webSession,
                                            ActionMessages msgs,
                                            ActionMessages warns,
                                            ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);
        FullEconomicsExcercisesForm form = (FullEconomicsExcercisesForm) actionForm;

        XlsPrinter xlsPrinter = new XlsPrinter();

        OutputStream out = null;
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            xlsPrinter.processFullEconomic(workbook, form
                    .getTeesf01FulleconomSelected(), request);
            xlsPrinter.processMacropart(workbook, form
                    .getTeesf01FulleconomSelected(), request);

            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + resources.getMessage("fullEconomicReport.fileName")
                    + ".xls");

            out = response.getOutputStream();
            workbook.write(out);
            out.flush();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (out != null)
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }

        return mapping.findForward("success");
    }

}
